package cruds;


import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.CompoundPropertyModel;

import home.Home;
import panels.BodyPanel;
import services.GenericService;
import staticmenus.StaticMenu;

@SuppressWarnings("serial")
public abstract class CrudCreateParent<T> extends BodyPanel{

	private GenericService<T> service;
	private T item;
	
	public CrudCreateParent(Home home) {
		super(home);
		this.initialize();
	}

	private void initialize() {
		this.initializeEmptyItem();
		this.initializeService();
		Form<T> form = new Form<T>("formCreate", new CompoundPropertyModel<T>(this.item));
		form.setOutputMarkupId(true);
		this.add(form);
		this.createFormFields(form);
		this.createSaveButton(form);
		this.createCancelButton(form);
	}


	private void createCancelButton(Form<T> form) {
		form.add(new AjaxSubmitLink("cancel"){

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				CrudCreateParent.this.redirectToPageIfCancel(target);
			}

			@Override
			protected void onError(AjaxRequestTarget target, Form<?> form) {
				
			}
		});
	}


	private void createSaveButton(Form<T> form) {
		form.add(new AjaxSubmitLink("create"){

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				CrudCreateParent.this.doSaveAndRedirect(target);
				CrudCreateParent.this.updatePage(target);
			}
			@Override
			protected void onError(AjaxRequestTarget target, Form<?> form) {
			
			}
		});
	}

	protected void updatePage(AjaxRequestTarget target) {
		this.updateDynamicMenu(target);
		StaticMenu menustatico = new StaticMenu(this.getHome());
		menustatico.changePanel(target);
	}
	
	protected abstract void initializeService();
	
	protected abstract void redirectToPageIfCancel(AjaxRequestTarget target);

	protected abstract void updateDynamicMenu(AjaxRequestTarget target);

	protected abstract void doSaveAndRedirect(AjaxRequestTarget target);

	protected abstract void createFormFields(Form<T> form);

	protected abstract void initializeEmptyItem();
	

	//----------Item
	public GenericService<T> getService() {
		return service;
	}

	public void setService(GenericService<T> service) {
		this.service = service;
	}

	public T getItem() {
		return item;
	}

	public void setItem(T item) {
		this.item = item;
	}

}
